package cn.hesion.leetcode;
/**
 * ClassName: MaxAncestorDiff <br/>
 * Description: <br/>
 * date: 2022/6/15 21:21<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */


/**
 *
 * @author: hesion
 * @create: 2022-06-15 21:21
 **/
public class MaxAncestorDiff {
    class Solution {
        public int maxAncestorDiff(TreeNode root) {
            int left = maxAncestorDiff(root.left, root.val, root.val);
            int right = maxAncestorDiff(root.right, root.val, root.val);
            return left > right ? left : right;
        }

        public int maxAncestorDiff(TreeNode root, int max, int min){
            if(root == null){
                return 0;
            }
            if(root.val > max){
                max = root.val;
            }
            else if(root.val < min){
                min = root.val;
            }
            if(root.left == null && root.right == null){
                return max - min;
            }
            int left = maxAncestorDiff(root.left, max, min);
            int right = maxAncestorDiff(root.right, max, min);
            return left > right ? left : right;
        }
    }
}
